package com.validate.platform.web.service.impl;

import com.alibaba.fastjson.JSON;
import com.validate.platform.web.model.ResultModel;
import com.validate.platform.web.model.ResultStatus;
import com.validate.platform.web.service.SmsValidateService;
import com.validate.platform.web.util.EhcacheUtil;
import com.validate.platform.web.util.PropertyConstants;
import com.validate.platform.web.util.SMSSendUtil;
import net.sf.ehcache.Element;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Random;
import java.util.UUID;

import com.google.common.collect.Maps;

/**
 * Created by YangJiyu on 2017/8/1 0001.
 */
@Service
public class SmsValidateServiceImpl implements SmsValidateService {

    Logger log = Logger.getLogger(this.getClass());

    @Override
    public String senValidateSms(Map<String, Object> paramMap) throws Exception {
        String result = "";
        String validateCode = generateValidateTemplate();
        Map<String, String> postParams = null;
        String sendType = paramMap.get("sendType").toString();
        String sendTypeContent = "";
        String content = "";
        if(sendType.equals("reg")){
            sendTypeContent = "注册";
            content = "[飞扬软件公司]验证码:"+validateCode+" ,感谢您注册飞扬软件微信小程序,["+sendTypeContent+"]验证码有效期为5分钟,请尽快输入.";
        }else if(sendType.equals("findPass")){
            sendTypeContent = "密码找回";
            content = "[飞扬软件公司]验证码:"+validateCode+" ,感谢您使用飞扬软件微信小程序,["+sendTypeContent+"]验证码有效期为5分钟,请尽快输入.";
        }else{
            sendTypeContent = "取款验证";
            content = "[飞扬软件公司]验证码:"+validateCode+" ,感谢您使用飞扬软件微信小程序."+sendTypeContent+"]验证码有效期为5分钟,请尽快输入.";
        }

        String tenant = paramMap.get("tenant").toString();
        String phone = paramMap.get("mobileNo").toString();
        try {
            Map<String, String> params = Maps.newHashMap();
            params.put("sendType","SMS");
            params.put("bizNo", UUID.randomUUID().toString());
            params.put("bizType","1");
            params.put("appPlatform", "BS");
            params.put("content", content);
            params.put("phone", phone);
            params.put("tenant", tenant);
            postParams = Maps.newHashMap();
            postParams.put("data", JSON.toJSONString(params));
        }catch (Exception e){

            log.error("租户：" + tenant + "，手机号：" + phone + "调用发送短信拼接参数失败：" + e.getMessage());
            throw new Exception("调用发送短信拼接参数失败");
        }
        try{
            log.info("租户：" + tenant + "，手机号：" + phone + "调用发送短信接口，参数为：" + JSON.toJSONString(postParams));
            String postResult = SMSSendUtil.post(PropertyConstants.getSendURL(), postParams);
            ResultModel resultModel = JSON.parseObject(postResult, ResultModel.class);
            String postResultString = "成功";
            if (resultModel != null && resultModel.getCode() == ResultStatus.SUCCESS.getCode()) {
                EhcacheUtil.getInstance().put("smsCache", phone, validateCode);
                result = validateCode;
            } else {

                postResultString = "失败";
            }
            log.info("租户：" + tenant + "短信发送" + postResultString + "，调用发送接口返回状态码：" + resultModel.getCode() + "信息：" + resultModel.getContent());
        }catch (Exception e){
            log.error("租户：" + tenant + "，手机号：" + phone + "post调用发送短信接收失败：" + e.getMessage());
            throw new Exception("post调用发送短信失败");
        }
        return result;
    }
    /**
     * 根据手机号和验证码进行缓存验证;
     * @param mobileNo,validateCode
     * @return String result;
     */

    public String validateByCode(String mobileNo,String validateCode)  {
        String result="";
        try{
            log.info("读取缓存：smsCache,EhcacheKey为：" + mobileNo);
            Element element=EhcacheUtil.getInstance().get("smsCache").get(mobileNo);
            if(null != element){
                if(element.getValue().equals(validateCode)){
                    result="success";
                }else{
                    result="error";
                }
            }else{
                result="null";
            }
        }catch (Exception e){
            log.info("读取缓存：smsCache,EhcacheKey为：" + mobileNo);
        }
        return result;
    }

    /**
     * 生成4位随机数字短信验证码;
     * @param
     * @return String 验证码;
     */
    public String generateValidateTemplate() {
        String str = "0123456789";
        StringBuilder validateCode = new StringBuilder(4);
        for (int i = 0; i < 4; i++) {
            char ch = str.charAt(new Random().nextInt(str.length()));
            validateCode.append(ch);
        }
        return validateCode.toString();
    }
}
